package me.sunpeng.volatiles;

/**
 * @author sp
 */
public class SafeDoubleCheckSingleton2 {
    private static volatile SafeDoubleCheckSingleton2 singleton;

    //私有化构造方法
    private SafeDoubleCheckSingleton2() {

    }

    //双重锁设计
    public static SafeDoubleCheckSingleton2 getInstance() {
        if (singleton == null){
            //1.多线程并发创建对象时，会通过加锁保证只有一个线程能创建对象
            synchronized (SafeDoubleCheckSingleton.class){
                if (singleton == null){
                    // 隐患：多线程并发创建对象时，会通过加锁保证只有一个线程能创建对象
                    singleton = new SafeDoubleCheckSingleton2();
                }
            }
        }
        //2.对象创建完毕，执行getInstance()将不需要获取锁对象，直接返回创建对象
        return singleton;
    }
}
